<?php

namespace app\roomcall\controller;

use app\common\model\Orderproject;
use app\common\model\Project;
use app\common\model\Room;
use app\common\model\Store;
use app\common\service\FeiEPrintService;
use app\common\service\PrintService;
use think\Db;
use think\Exception;

/**
 * 前台首页控制器
 * @package app\index\controller
 */
class Index extends Home
{
    public $noNeedLogin = [''];

    /**
     * 首页接口
     **/
    public function index()
    {
        if ($this->request->isPost()) {
            $room_id = $this->request->post('room_id');
            if (empty($room_id)) {
                $this->result('房间ID不能为空', '', 204);
            }
            $room = Room::where('id', $room_id)->find();
            $orderprojectModel = new Orderproject();
            $nowproject = $orderprojectModel->getRoomProject($this->store_id, $room_id, $this->userInfo['id']);
//            dump($this->userInfo['id']);
//            dump($room_id);
//            dump($nowproject);
            $order = Db::name('qt_order')
                ->field('u.real_name')
                ->alias('o')
                ->leftJoin('qt_users u', 'u.id = o.cashier_id')
                ->where('o.room_id', $room['id'])->find();

            $data = array(
                'nowproject' => $nowproject,
                'store_name' => Store::where('id', $this->store_id)->value('name'),
                'room_name' => $room['name'],
                'cashier_name' => $order['real_name'] ?? '',
            );
            $this->result('获取成功', $data, 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 房间状态
     */
    public function room_status()
    {
        if ($this->request->isPost()) {
            $page = $this->request->post('page', '1');
            $limit = $this->request->post('limit', '10');
            $type = $this->request->post('type', '0');
            $keyword = $this->request->post('keyword', '0');
            $RoomModel = new Room();
            $list = $RoomModel->roomlist($type, $page, $limit, $keyword, $this->store_id);
            $info = array(
                'list' => $list
            );
            $this->result('成功', $info, '200');
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 房间详情
     */
    public function room_info()
    {

        if ($this->request->isPost()) {
            $room_id = $this->request->post('room_id');
            if (empty($room_id)) {
                $this->result('房间ID不能为空', '', 204);
            }
            $RoomModel = new Room();
            $list = $RoomModel->roominfo($room_id, $this->store_id);
            $info = array(
                'list' => $list
            );
            $this->result('成功', $info, '200');
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 获取用户房间结账支付
     */
    public function pay()
    {

        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $map = [];
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            if (empty($getData['viper_card_id'])) {
                $getData['viper_card_id'] = '';
            }
            if (empty($getData['viper_card_money'])) {
                $getData['viper_card_money'] = '';
            }
            if (!empty($getData['project_order_total_id'])) {
                $map[] = ['project_order', '=', $getData['project_order_total_id']];
            }
            if (!empty($getData['goods_order_total_id'])) {

                $map[] = ['goods_order', '=', $getData['goods_order_total_id']];
            }
            //备注默认为空
            if (!isset($getData['content']) || empty($getData['content'])) {
                $getData['content'] = '';
            }
            if (!isset($getData['activity_id']) || empty($getData['activity_id'])) {
                $getData['activity_id'] = '';
            }
            if (!isset($getData['cashier_remarks']) || empty($getData['cashier_remarks'])) {
                $getData['cashier_remarks'] = '';
            }
            if (!isset($getData['pay_content']) || empty($getData['pay_content'])) {
                $getData['pay_content'] = '';
            }
            if (!isset($getData['engineer_ids']) || empty($getData['engineer_ids'])) {
                $getData['engineer_ids'] = '';
            }
            if (!isset($getData['project_ids']) || empty($getData['project_ids'])) {
                $getData['project_ids'] = '';
            }

            $room_log = Db::name('qt_room_log')->where('room_id', $getData['room_id'])->order('id desc')->limit(1)->find();
            $find = Db::name('qt_check_out')->where($map)->where('is_revoke', '2')->find();
            if (empty($find)) {
                //构建主结算订单
                $checkOutInsert = [
                    'store_id' => $this->userInfo['store_id'],
                    'room_id' => $getData['room_id'],
                    'engineer_ids' => $getData['engineer_ids'],
                    'project_ids' => $getData['project_ids'],
                    'order_no' => check_order_sn(),
                    'project_order' => $getData['project_order_total_id'],
                    'goods_order' => $getData['goods_order_total_id'],
                    'viper_card_id' => $getData['viper_card_id'],
                    'viper_card_money' => $getData['viper_card_money'],
                    'total_money' => $getData['total_money'],
                    'payment_money' => $getData['payment_money'],
                    'cashier_id' => $this->userInfo['id'],
                    'cashier_time' => time(),
                    'activity_id' => $getData['activity_id'],
                    'cashier_remarks' => $getData['cashier_remarks'],
                    'pay_content' => $getData['pay_content'],
                    'open_room_time' => $room_log['created_time'],
                ];
                $checkOutId = Db::name('qt_check_out')->insertGetId($checkOutInsert);
            } else {
                $checkOutId = $find['id'];
            }

            check_out_pay_all($getData['pay_content'], $checkOutId, $this->userInfo, '2');

            //会员卡结算 card_pay_type 1 会员卡余额 2 次卡 3 月卡
            if (isset($getData['card_data']) && !empty($getData['card_data'])) {
                $cardData = json_decode($getData['card_data'], true);
                foreach ($cardData as $key => $value) {
                    //会员次卡结账
                    if ($value['card_pay_type'] == '2') {
                        $this->pay_number_card($value, $checkOutId);
                        $this->pay_card($value, $checkOutId);
                    } elseif ($value['card_pay_type'] == '3') {
                        //会员月卡结账
                        $this->pay_month_card($value, $checkOutId);
                        $this->pay_card($value, $checkOutId);
                    } elseif ($value['card_pay_type'] == '1') {
                        //会员卡结账
                        $this->pay_card($value, $checkOutId);
                    }
                }
            }

            //项目计算
            $projectRes = json_decode($getData['project'], true);
            $totalProjectPrice = 0;
            $projectInsert = [];
            foreach ($projectRes as $key => $value) {
                $projectInsert[$key] = [
                    'activity_id' => $getData['activity_id'],
                    'link_id' => $value['project_id'],
                    'link_type' => '1',
                    'check_out_id' => $checkOutId,
                    'receivable' => $value['payment_price'],
                    'actual_receipt' => $value['activity_price'],
                    'total_num' => 1,
                ];
                $totalProjectPrice += $value['payment_price'];
                if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                    $value['is_discount'] = 0;
                }
                Db::name('qt_order_project')->where('id', $value['project_order_id'])->update([
                    'payment_price' => $value['payment_price'],
                    'is_discount' => $value['is_discount'],
                    'pay_status' => '1',
                    'pay_time' => time()
                ]);
                //更新提成记录时间
                Db::name('qt_commission_log')
                    ->where(['order_project_id' => $value['project_order_id'], 'type' => '1'])
                    ->update(['updated_time' => time()]);
            }


            //商品数据插入
            $totalGoodsPrice = 0;
            $goodsRes = json_decode($getData['goods'], true);
            if (empty($goodsRes)) {
                $goodsInsert = [];
            }
            foreach ($goodsRes as $key => $value) {
                $goodsInsert[$key] = [
                    'activity_id' => $getData['activity_id'],
                    'link_id' => $value['goods_id'],
                    'link_type' => '2',
                    'check_out_id' => $checkOutId,
                    'receivable' => $value['payment_price'],
                    'actual_receipt' => $value['activity_price'],
                    'total_num' => $value['goods_num'],
                ];
                $totalGoodsPrice += $value['payment_price'];
                if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                    $value['is_discount'] = 0;
                }
                Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->update([
                    'payment_price' => $value['payment_price'],
                    'is_discount' => $value['is_discount'],
                    'pay_status' => '1'
                ]);
                //更新提成记录时间
                Db::name('qt_commission_log')
                    ->where(['order_project_id' => $value['product_order_id'], 'type' => '2'])
                    ->update(['updated_time' => time()]);

            }
            //查询技师是否在房间内
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();
            //判断房间是否还有未结账的项目子订单如果没有更新总订单
            $checkProjectOrder = Db::name('qt_order_project')->where('is_delete',2)->where(['order_id' => $getData['project_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkProjectOrder)) {
                //如果技师没在房间内，更新总项目订单的状态
                if (empty($engineerStatus)) {
                    //更新项目总订单
                    Db::name('qt_order')->where('id', $getData['project_order_total_id'])->update([
                        'payment_price' => $totalProjectPrice,
                        'pay_status' => 2,
                        'pay_time' => time(),
                    ]);
                }
            }

            //判断房间是否还有未结账的商品子订单如果没有更新总订单
            $checkPGoodsOrder = Db::name('qt_product_order_item')->where(['order_id' => $getData['goods_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkPGoodsOrder)) {
                //更新项目总订单
                Db::name('qt_product_order')->where('id', $getData['goods_order_total_id'])->update([
                    'payment_price' => $totalGoodsPrice,
                    'order_status' => 1,
                    'pay_time' => time(),
                    'pay_status' => 1
                ]);
            }

            //插入结算子表
            $subOrderInsert = array_merge($projectInsert, $goodsInsert);
            Db::name('qt_check_out_item')->insertAll($subOrderInsert);

            //判断房间是否有技师
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();

            //如果没有，更新房间状态
            if (empty($engineerStatus)) {
                //自动脏房
                if ($this->storeInfo['is_auto_dirty_room'] == '1') {
                    Db::name('qt_room')->where('id', $getData['room_id'])->update(['status_id' => '5']);
                }
            }

            if ($getData['total_money'] == '0') {
                if ($this->storeInfo['is_print_zero_order'] == '1') {
                    //调用结算打印
                    FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
                }
            } else {
                //调用结算打印
                //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
            }
            $result = PrintService::printPcBill($checkOutId,$this->userInfo);
            $this->result('结算成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }


}
